#include "widget.h"
#include "ui_widget.h"

#include<QMessageBox>
#include<QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    socket = new QUdpSocket(this);
    this->setWindowTitle("服务器");

    //连接信号槽
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processRequest);

    //绑定端口号,必须在绑定端口号之前链接信号槽
    bool ret = socket->bind(QHostAddress::Any,9090);
    if(!ret)
    {
        //绑定失败
        QMessageBox::critical(this,"服务器启动出错",socket->errorString());
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::processRequest()
{
    //1、读取数据
    const QNetworkDatagram& requestDatagram = socket->receiveDatagram();
    //2、解析
    QString request = requestDatagram.data();
    //3、根据请求计算响应（回显服务器，响应不需要计算，就是请求本身）
    const QString& response = process(request);
    //4、把响应发送给客户端
    QNetworkDatagram responseDategram(response.toUtf8(), requestDatagram.senderAddress(), requestDatagram.senderPort());
    socket->writeDatagram(responseDategram);

    // 把这次交互的信息, 显示到界面上.
     QString log = "[" + requestDatagram.senderAddress().toString() + ":" + QString::number(requestDatagram.senderPort())
               + "] req: " + request + ", resp: " + response;
     ui->listWidget->addItem(log);
}

QString Widget::process(const QString &request)
{
      return request;
}

